package com.lcz.manage.util.event.publisher.impl;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executor;

import com.google.common.collect.Lists;
import com.lcz.manage.util.event.event.Event;
import com.lcz.manage.util.event.listener.Listener;
import com.lcz.manage.util.event.publisher.EventPublisher;
import com.lcz.manage.util.event.publisher.listener.EventCallbackListener;

/**
 * @author xingyongjiang@yunrong.cn
 * @version V3.0
 * @since 2021/4/20 10:29
 */
public abstract class AbstractEventPublisher implements EventPublisher {

    protected List<Listener> listenerList = Lists.newArrayList();

    /**
     * 发送事件
     *
     * @param event
     */
    @Override
    public void publish(Event event) {

        Executor executor = getExecutor();
        if (Objects.isNull(executor)) {
            listenerList.stream()
                .filter(listener -> listener.acceptEvent(event))
                .forEach(listener -> listener.handleEvent(event));
        } else {
            listenerList.stream()
                .filter(listener -> listener.acceptEvent(event))
                .forEach(listener -> executor.execute(() -> listener.handleEvent(event)));
        }
    }

    /**
     * 发送事件
     *
     * @param event
     * @param listener
     */
    @Override
    public void publish(Event event, EventCallbackListener listener) {
        try {
            publish(event);
            listener.publishSuccess();
        } catch (Exception ex) {
            listener.publishFail();
        }
    }

    /**
     * 设置监听器
     *
     * @param listener
     */
    @Override
    public synchronized void setListener(Listener listener) {
        listenerList.add(listener);
    }

    /**
     * 获取执行器
     *
     * @return
     */
    protected abstract Executor getExecutor();
}